/* eslint-disable @typescript-eslint/consistent-type-imports */
/* eslint-disable react/self-closing-comp */
import {
  createOneAPI,
  delByIdAPI,
  deleteManyAPI,
  loadDataAPI,
  updataByIdAPI,
} from '@/services/articles';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProFormText,
  ProTable,
  ProForm,
  ProFormSelect,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, message, Popconfirm, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { loadAllDataAPI } from '@/services/articles-categories';

import { dalImg } from '@/utils/tools';
import MyUpload from '@/components/MyUpload';
function Articles() {
  const [currentId, setCurrentId] = useState(''); //当前id，默认是空，表示新增
  const actionRef = useRef<ActionType>();
  // eslint-disabl e-next-line @typescript-eslint/no-unused-vars
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [categories, setCategories] = useState({}); //分类数据
  const [imageUrl, setImageUrl] = useState<any>(''); //文件上传的图片信息
  const [myForm] = ProForm.useForm();
  useEffect(() => {
    loadAllDataAPI().then((res) => {
      const obj = {}; //动态的设置属性
      res.data.list.forEach((item: any) => {
        obj[item.id] = item.name;
      });
      setCategories(obj);
    });
  }, []);
  useEffect(() => {
    //关闭模态框的时候，清空数据
    if (!createModalVisible) {
      setCurrentId('');
      setImageUrl('');
    }
  }, [createModalVisible]);
  return (
    <>
      <PageContainer>
        <ProTable
          rowKey="id"
          // 可以直接设置request属性，为一个function
          // 他的返回值中的数据可以直接绑定显示
          // 如果我们改变了查询条件，会自动的传递过去，进行调接口
          request={loadDataAPI}
          actionRef={actionRef}
          // rowSelection 加上他之后可以实现批量删除
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [],
            defaultSelectedRowKeys: [1],
          }}
          //自定义选择之后的操作提示
          tableAlertOptionRender={({ selectedRowKeys }: any) => {
            return (
              <Space size={16}>
                <Popconfirm
                  title="是否确认删除选中的内容？"
                  onConfirm={async () => {
                    if (selectedRowKeys > 0) await deleteManyAPI(selectedRowKeys.join(','));
                    actionRef.current?.reload();
                  }}
                >
                  <a>批量删除</a>
                </Popconfirm>

                {/* <a>导出数据</a> */}
              </Space>
            );
          }}
          columns={[
            {
              title: '序号',
              hideInSearch: true, //表示不在顶部查询中显示
              width: 80,
              align: 'center',
              render(v, r, i) {
                return i + 1;
              },
            },
            {
              title: '名字',
              dataIndex: 'name', //这个会在查询的时候会自动作为属性名
            },
            {
              title: '分类',
              dataIndex: 'category',
              valueType: 'select',
              valueEnum: categories,
              render(v: any, r: any) {
                return r.category?.name;
              },
            },
            {
              title: '描述',
              dataIndex: 'desc',
              hideInSearch: true, //表示不在顶部查询中显示
            },
            {
              title: '封面',
              // dataIndex: 'desc',
              hideInSearch: true, //表示不在顶部查询中显示
              render(v: any) {
                return <img className="t-img" src={dalImg(v.img)} />;
              },
            },
            {
              title: '操作',
              width: 100,
              hideInSearch: true, //表示不在顶部查询中显示
              render(v: any) {
                return (
                  <Space>
                    <Button
                      type="primary"
                      size="small"
                      icon={<EditOutlined />}
                      onClick={() => {
                        setCurrentId(v.id); //设置当前id
                        setImageUrl(v.image); //设置图片
                        handleModalVisible(true); //弹出model
                        myForm.setFieldsValue(v); //设置表单的默认值
                      }}
                    ></Button>
                    <Popconfirm
                      title="是否确认删除？"
                      onConfirm={async () => {
                        await delByIdAPI(v.id);
                        actionRef.current?.reload();
                      }}
                    >
                      <Button type="primary" size="small" icon={<DeleteOutlined />} danger></Button>
                    </Popconfirm>
                  </Space>
                );
              },
            },
          ]}
          toolBarRender={() => {
            return [
              <Button
                key={1}
                type="primary"
                icon={<PlusOutlined />}
                size="small"
                onClick={() => {
                  handleModalVisible(true);
                  console.log(1);
                }}
              >
                新增
              </Button>,
            ];
          }}
        />
      </PageContainer>

      <ModalForm
        form={myForm}
        title="编辑"
        // modalProps表示设置模态框的数据
        modalProps={{ destroyOnClose: true }}
        preserve={false}
        visible={createModalVisible}
        onFinish={async (v) => {
          if (currentId) {
            await updataByIdAPI(currentId, { ...v, image: imageUrl }); //修改
          } else {
            await createOneAPI({ ...v, image: imageUrl }); //新增
          }
          message.success('保存成功');
          handleModalVisible(false);
          actionRef.current?.reload(); //重新加载数据的意思
        }}
        //onVisibleChange可见性改变的时候执行，（点击取消后模态框消失）
        onVisibleChange={handleModalVisible}
      >
        <ProFormText
          rules={[{ required: true, message: '名字不能为空' }]}
          placeholder="请输入内容"
          name="name"
          label="标题"
        ></ProFormText>
        <ProFormSelect
          label="请输入分类"
          name="articleCategoryId"
          valueEnum={categories}
          rules={[{ required: true, message: '分类不能为空' }]}
        ></ProFormSelect>
        <ProForm.Item label="主图">
          <MyUpload imageUrl={imageUrl} setImageUrl={setImageUrl}></MyUpload>
        </ProForm.Item>
        <ProFormTextArea placeholder="请输入简介" label="简介" name="desc"></ProFormTextArea>
      </ModalForm>
    </>
  );
}

export default Articles;
